/**
$Id: pion-glue.cpp 3096 2010-07-06 07:21:14Z Bear $

Copyright (c) 2010 Nuwa Information Co., Ltd, and individual contributors.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

  3. Neither the name of Nuwa Information nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

$Author: Bear $
$Date: 2010-07-06 15:21:14 +0800 (星期二, 06 七月 2010) $
$Revision: 3096 $
*/
/// Based on ajp-glue.c
/*-
 * Copyright (c) 2006 Allan Saddi <allan@saddi.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Id: pion-glue.cpp 3096 2010-07-06 07:21:14Z Bear $
 */

#include <Python.h>

#include <assert.h>

#ifdef _TRACE
#include <iostream>

#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

boost::mutex	traceMutex;
#endif

#include "WsgiService.hpp"
#include "pion-glue.hpp"
#include "wsgi-int.h"

using pion::plugins::WsgiContext;
using pion::plugins::WsgiService;
using pion::plugins::WsgiSendHandler;
using pion::net::HTTPRequestPtr;
using pion::net::HTTPTypes;
using pion::net::TCPConnectionPtr;
using pion::net::HTTPResponseWriterPtr;
using pion::net::HTTPResponse;

const int unquoteURL = 1;

/* Populate WSGI environ dictionary */
int wsgiPopulateEnviron(Request *self)
{
 HTTPRequestPtr& req = ((WsgiContext *)self->context)->request;
 WsgiService* srv = ((WsgiContext *)self->context)->service;

#ifdef _TRACE
 {
  boost::mutex::scoped_lock lock(traceMutex);
  std::cout << "[TRACE] wsgiPopulateEnviron" << std::endl;
 }
#endif

 PyObject *env = self->env;
 PyObject *val;
 int ret, j, k;
 const char *pathInfo, *req_uri = NULL;
 char buf[256];

 if(wsgiPutEnv(self, "REQUEST_METHOD", req->getMethod().c_str()))
  return -1;
  
 if(wsgiPutEnv(self, "SERVER_PROTOCOL", req->getVersionString().c_str()))
  return -1;

 struct PyMemRAII
 {
  void* p;
  PyMemRAII(void* _p) : p(_p) {};
  ~PyMemRAII() 
  {
   if(p)
    PyMem_Free(p); 
  };
 };

 if(unquoteURL) 
 {
  if((req_uri = wsgiUnquote(req->getOriginalResource().c_str())) == NULL) 
  {
   PyErr_NoMemory();
   return -1;
  }
 }

 PyMemRAII _req_uri((void*)req_uri);

 if(wsgiPutEnv(self, "REQUEST_URI", 
               req_uri ? req_uri : req->getOriginalResource().c_str()))
  return -1;
  
 if(wsgiPutEnv(self, "REMOTE_ADDR", req->getRemoteIp().to_string().c_str()))
  return -1;
  
 if(wsgiPutEnv(self, "REMOTE_HOST", req->getRemoteIp().to_string().c_str()))
   return -1;

 if(wsgiPutEnv(self, "SERVER_NAME", srv->getName().c_str()))
  return -1;

 if(wsgiPutEnv(self, "SERVER_PORT", srv->getPort().c_str()))
  return -1;

 /* HTTP headers */
 HTTPTypes::Headers::iterator iter = req->getHeaders().begin();
 HTTPTypes::Headers::iterator iend = req->getHeaders().end();
 for(; iter != iend; iter++)
 {
  const char *header = (*iter).first.c_str();
  const char *value = (*iter).second.c_str();

  /* Copy/convert header name */
  strcpy(buf, "HTTP_");

  k = strlen(header);
  if(k > (sizeof(buf) - 6))
   k = sizeof(buf) - 6;
  
  for(j = 0; j < k; j++) 
  {
   if(header[j] == '-')
    buf[5 + j] = '_';
   else
    buf[5 + j] = toupper(header[j]);
  }

  buf[5 + j] = '\0';

  if(!strcmp(buf, "HTTP_CONTENT_TYPE") || 
     !strcmp(buf, "HTTP_CONTENT_LENGTH")) 
  {
   /* Strip HTTP_ */
   if(wsgiPutEnv(self, &buf[5], value))
	   return -1;
  }
  else 
  {
   if(wsgiPutEnv(self, buf, value))
	   return -1;
  }
 }

 /* wsgi.version */
 if((val = Py_BuildValue("(ii)", 1, 0)) == NULL)
  return -1;  
 ret = PyDict_SetItemString(env, "wsgi.version", val);
 Py_DECREF(val);
 if(ret)
  return -1;

 /* wsgi.input */
 if(PyDict_SetItemString(env, "wsgi.input", self->input))
  return -1;

 /* wsgi.errors */
 if(PyDict_SetItemString(env, "wsgi.errors", wsgiStderr))
  return -1;

 /* wsgi.multithread */
 if(PyDict_SetItemString(env, "wsgi.multithread", Py_True))
  return -1;

 /* wsgi.multiprocess */
 if(PyDict_SetItemString(env, "wsgi.multiprocess", Py_False))
  return -1;

 /* wsgi.run_once */
 if(PyDict_SetItemString(env, "wsgi.run_once", Py_False))
  return -1;

 /* wsgi.url_scheme */
 if(wsgiPutEnv(self, "wsgi.url_scheme", "http"))
  return -1;

 if(PyDict_SetItemString(env, "wsgi.file_wrapper", 
                         (PyObject *)&FileWrapper_Type))
  return -1;

 /* SCRIPT_NAME/PATH_INFO */
 pathInfo = req_uri ? req_uri : req->getOriginalResource().c_str();
 if(wsgiScriptNameLen) 
 {
  if(!strncmp(pathInfo, wsgiScriptName, wsgiScriptNameLen))
   pathInfo = &pathInfo[wsgiScriptNameLen];
  else
   fprintf(stderr, "WARNING: SCRIPT_NAME does not match REQUEST_URI\n");
 }

 if(wsgiPutEnv(self, "PATH_INFO", pathInfo))
  return -1;

 if(wsgiPutEnv(self, "SCRIPT_NAME", wsgiScriptName))
  return -1;

 /* Ensure QUERY_STRING is set */
 if(!PyDict_GetItemString(self->env, "QUERY_STRING")) 
 {
  if(wsgiPutEnv(self, "QUERY_STRING", req->getQueryString().c_str()))
   return -1;
 }

 return 0;
}

/* Send HTTP response headers. */
int wsgiSendHeaders(void *ctxt, int statusCode, const char *statusMsg,
		                  int headerCount, const char *headers[])
{
#ifdef _TRACE
 {
  boost::mutex::scoped_lock lock(traceMutex);
  std::cout << "[TRACE] wsgiSendHeaders(" << ctxt << ", " << 
   statusCode << ", " << statusMsg << ", " << headerCount << ")" << std::endl;
 }
#endif

 Py_BEGIN_ALLOW_THREADS

 HTTPResponseWriterPtr& response = ((WsgiContext *)ctxt)->response;
 HTTPResponse& res = response->getResponse();

 res.setStatusCode(statusCode);
 res.setStatusMessage(statusMsg);
 for(int i = 0; i < headerCount; i++)
 {
  int j = 2 * i;
  res.addHeader(headers[j], headers[j + 1]);
 }

 Py_END_ALLOW_THREADS

 return 0;
}

/* Send HTTP response body. */
int wsgiSendBody(void *ctxt, const uint8_t *data, size_t len)
{
#ifdef _TRACE
 {
  boost::mutex::scoped_lock lock(traceMutex);
  std::cout << "[TRACE] wsgiSendBody(" << ctxt << ", [DATA], " << 
   len << ")" << std::endl;
 }
#endif

 Py_BEGIN_ALLOW_THREADS

 HTTPRequestPtr& request = ((WsgiContext *)ctxt)->request;
 HTTPResponseWriterPtr& response = ((WsgiContext *)ctxt)->response;
 WsgiSendHandler& handler = ((WsgiContext *)ctxt)->sendHandler;

 // #1176. Too large chunk can't be write at once.
 bool http10 = request->getVersionString() == "HTTP/1.0";
 char* p = (char*)(const_cast<uint8_t*>(data));
 while(len)
 {
  int chunkLen = len > 32768 ? 32768 : len;
  len -= chunkLen;

  response->write((void*)p, chunkLen);
  ((WsgiContext *)ctxt)->sentBytes += chunkLen;
  if(!http10)
  {
   response->sendChunk(
    boost::bind(boost::ref(handler),
     boost::asio::placeholders::error,										
	  		boost::asio::placeholders::bytes_transferred));
   response->clear();
  }

  p += chunkLen;
 }

 Py_END_ALLOW_THREADS

 return 0;
}

/* Send a file as the HTTP response body. */
int wsgiSendFile(void *ctxt, int fd)
{
#ifdef _TRACE
 {
  boost::mutex::scoped_lock lock(traceMutex);
  std::cout << "[TRACE] wsgiSendFile(" << ctxt << ", " << 
   fd << ")" << std::endl;
 }
#endif

 // TODO: Test it.

 Py_BEGIN_ALLOW_THREADS

 boost::scoped_array<uint8_t> buf(new uint8_t[10240]);
 int readLen;

 do 
 {
  if((readLen = read(fd, buf.get(), 8192)) < 0)
   return -1;

  buf[readLen] = '\0';
  if(wsgiSendBody(ctxt, buf.get(), readLen))
   return -1;
 }
 while(readLen == 8192);

 Py_END_ALLOW_THREADS

 return 0;
}

/* Receive a request body chunk from the transport layer. */
int wsgiGetBody(void *ctxt)
{
#ifdef _TRACE
 {
  boost::mutex::scoped_lock lock(traceMutex);
  std::cout << "[TRACE] wsgiGetBody(" << ctxt << ")" << std::endl;
 }
#endif

 /*
 Py_BEGIN_ALLOW_THREADS
  
 HTTPRequestPtr& req = ((WsgiContext *)ctxt)->request;

 Py_END_ALLOW_THREADS
 */

 return 0;
}

/* Primes the input stream, if needed by transport layer. (AJP sends the
   first request body chunk if Content-Length is non-zero.) */
int wsgiPrimeInput(void *ctxt)
{
#ifdef _TRACE
 {
  boost::mutex::scoped_lock lock(traceMutex);
  std::cout << "[TRACE] wsgiPrimeInput(" << ctxt << ")" << std::endl;
 }
#endif

 HTTPRequestPtr& req = ((WsgiContext *)ctxt)->request;

 int bufLen = req->getContentLength();
 if(bufLen)
 {
  int ret = 0;

  Py_BEGIN_ALLOW_THREADS

  ret = wsgiBodyHandler(ctxt, (uint8_t*)req->getContent(), bufLen);

  Py_END_ALLOW_THREADS

  return ret;
 }

 return 0;
}

/* Set application-specific (WSGI) request-level data. */
void wsgiSetRequestData(void *ctxt, void *data)
{
 ((WsgiContext *)ctxt)->data = data;
}

/* Get application-specific (WSGI) request-level data. */
void *wsgiGetRequestData(void *ctxt)
{
 return ((WsgiContext *)ctxt)->data;
}

/* Return the Content-Length associated with this request. */
int wsgiGetContentLength(void *ctxt)
{
 return ((WsgiContext *)ctxt)->request->getContentLength();
}
